package com.ym.student.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ym.student.system.entity.SysRoleMenu;
import com.ym.student.system.mapper.SysRoleMenuMapper;
import com.ym.student.system.service.ISysRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ym
 * @since 2025-05-28
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Override
    public List<Integer> getMenuIdsByRoleId(Integer roleId) {

        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);

        List<SysRoleMenu> roleMenus = this.list(wrapper);

        List<Integer> menuIds = new ArrayList<>();
        for (SysRoleMenu roleMenu : roleMenus) {
            menuIds.add(roleMenu.getMenuId());
        }
        return menuIds;

//        return roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
    }

    @Override
    public void assignMenusToRole(Integer roleId, List<Integer> menuIds) {

        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        // 删除原有关联
        this.remove(wrapper);

        // lambda表达式 批量保存数据到角色菜单关联表
        if (menuIds != null && !menuIds.isEmpty()) {
            // 构建新的关联
            List<SysRoleMenu> list = menuIds.stream()
                    .map(menuId -> {
                        SysRoleMenu rm = new SysRoleMenu();
                        rm.setRoleId(roleId);
                        rm.setMenuId(menuId);
                        return rm;
                    })
                    .collect(Collectors.toList());

            // 批量插入
            baseMapper.insert(list);
        }
    }

}